﻿using System;
using System.Data;
using System.Text;
using System.Collections.Generic;
using System.Data.OracleClient;
using GSLMS.Entity;
namespace GSLMS.DAL.Oracle
{

    public partial class SYS_Dict
    {
       private readonly GSLMS.Core.Loger log = new Core.Loger();

       public List<Dictionary> GetAll(int langType = 0)
       {
           var list = new List<Dictionary>();
           DataTable dt = null;
           string sqlWhere = "";

           if (langType > -1)
               sqlWhere = " status=" + langType.ToString();

           dt = OracleHelper.DataTableFileter(GetAllByCache(), sqlWhere, " datatype,sortno asc");
           if (dt != null && dt.Rows.Count > 0)
           {
               for (int i = 0; i < dt.Rows.Count; i++)
               {
                   Dictionary model = new Dictionary();
                   model = DataRowToModel(dt.Rows[i]);
                   list.Add(model);
               }
           }
          
           return list;
       }

       public List<Dictionary> GetByGroupName(string groupName, int langType = 0)
       {
           var list = new List<Dictionary>();
           DataTable dt = null;
           string sqlWhere="";
           sqlWhere= " datatype='"+groupName+"' ";
           if(langType>-1)
               sqlWhere+="and status=" + langType.ToString();

           dt = OracleHelper.DataTableFileter(GetAllByCache(),sqlWhere, " sortno asc");
           if (dt != null && dt.Rows.Count > 0)
           {
               for (int i = 0; i < dt.Rows.Count; i++)
               {
                   Dictionary model = new Dictionary();
                   model = DataRowToModel(dt.Rows[i]);
                   list.Add(model);
               }
           }
           

           return list;
       }

       public List<Dictionary> GetAll(Dictionary searchparma)
       {
           var list = new List<Dictionary>();
           DataTable dt = null;
           string sqlWhere = " 1=1 ";

           if (searchparma.ID != null && searchparma.ID > 0)
               sqlWhere += " and id=" + searchparma.ID.ToString();
           if (searchparma.GroupName != null && searchparma.GroupName != "")
               sqlWhere += " and datatype='"+searchparma.GroupName+"'";
           if (searchparma.key != null && searchparma.key != "")
               sqlWhere += " and datacode='" + searchparma.key + "'";
           if (searchparma.LangType != null && searchparma.LangType > -1)
               sqlWhere += " and status=" + searchparma.LangType.ToString();
           if (searchparma.Value != null && searchparma.Value != "")
               sqlWhere += " and datavalue='" + searchparma.Value + "'";


           dt = OracleHelper.DataTableFileter(GetAllByCache(),sqlWhere, "");
           if (dt != null && dt.Rows.Count > 0)
           {
               for (int i = 0; i < dt.Rows.Count; i++)
               {
                   Dictionary model = new Dictionary();
                   model = DataRowToModel(dt.Rows[i]);
                   list.Add(model);
               }
           }
           

           return list;
       }

       public Dictionary GetByID(string key, int langType = 0)
       {
           //不再使用
           return null;
       }

       public Dictionary GetByID(string groupname, string key, int langType = 0)
       {
           DataTable dt = null;
           string sqlWhere="";
           sqlWhere= " datatype='" + groupname + "' and datacode='"+key+"'";
           if(langType>-1)
               sqlWhere+=" and status=" + langType.ToString();

           dt = OracleHelper.DataTableFileter(GetAllByCache(),sqlWhere, "");
           if (dt != null && dt.Rows.Count > 0)
           {
             return  DataRowToModel(dt.Rows[0]);
           }
           else
               return null;
       }


        /// <summary>
        /// 新增数据字典，1成功，0失败，-1编号已经存在，-2名称已经存在
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
       public int  Add(Dictionary model)
       {
           int num = 0;
           OracleParameter[] parms = new OracleParameter[]{
								new OracleParameter("P_ID", model.ID),
								new OracleParameter("P_PID", model.PID),
								new OracleParameter("P_DATATYPE", model.GroupName),
								new OracleParameter("P_DATACODE", model.key),
								new OracleParameter("P_DATAVALUE", model.Value),
								new OracleParameter("P_SORTNO", model.SortNo),
                                new OracleParameter("P_STATUS", model.LangType),
                                new OracleParameter("returnvalue",OracleType.Int32)
                            };

           for (int i = 0; i < 7; i++)
           {
               parms[i].Direction = ParameterDirection.Input;
           }
           parms[7].Direction = ParameterDirection.Output;

           try
           {
               OracleHelper.ExecuteNonQuery(OracleHelper.connectionString, CommandType.StoredProcedure, "pkg_sys.proc_dist_add", parms);
               if (parms[7].Value != DBNull.Value)
                   num = OracleHelper.ToInt(parms[7].Value.ToString());

               //清除缓存
               OracleHelper.RemoveCacheObject("_DistList");

           }
           catch (Exception ex)
           {
               log.ExceptionHand(ex);
           }

           return num;
       }

       /// <summary>
       /// 编辑数据字典，1成功，0失败，-1编号已经存在，-2名称已经存在
       /// </summary>
       /// <param name="model"></param>
       /// <returns></returns>
       public int Update(Dictionary model)
       {
           int num = 0;
           OracleParameter[] parms = new OracleParameter[]{
								new OracleParameter("P_ID", model.ID),
								new OracleParameter("P_PID", model.PID),
								new OracleParameter("P_DATATYPE", model.GroupName),
								new OracleParameter("P_DATACODE", model.key),
								new OracleParameter("P_DATAVALUE", model.Value),
								new OracleParameter("P_SORTNO", model.SortNo),
                                new OracleParameter("P_STATUS", model.LangType),
                                new OracleParameter("returnvalue",OracleType.Int32)
                            };

           for (int i = 0; i < 7; i++)
           {
               parms[i].Direction = ParameterDirection.Input;
           }
           parms[7].Direction = ParameterDirection.Output;

           try
           {
               OracleHelper.ExecuteNonQuery(OracleHelper.connectionString, CommandType.StoredProcedure, "pkg_sys.proc_dist_update", parms);
               if (parms[7].Value != DBNull.Value)
                   num = OracleHelper.ToInt(parms[7].Value.ToString());

               //清除缓存
               OracleHelper.RemoveCacheObject("_DistList");

           }
           catch (Exception ex)
           {
               log.ExceptionHand(ex);
           }

           return num;
       }

       /// <summary>
       /// 删除字典信息
       /// </summary>
       /// <param name="key"></param>
       /// <param name="groupName"></param>
       /// <returns></returns>
       public bool Delete(string key, string groupName)
       {
           bool flag = false;
           string sql = "";
           sql = " delete from tb_sys_dist where datatype='"+groupName+"' and datacode='"+key+"'";

           try
           {
               int num = OracleHelper.ExecuteNonQuery(sql);
               if (num == 1)
               {
                   flag = true;
                   //清除缓存
                   OracleHelper.RemoveCacheObject("_DistList");
               }
           }
           catch (Exception ex)
           {
               log.ExceptionHand(ex);
           }

           return flag;
       }

       /// <summary>
       ///DataRowToModel 
       /// </summary>
       private Dictionary DataRowToModel(DataRow dr)
       {
           if (dr != null && dr.ItemArray.Length > 0)
           {
               GSLMS.Entity.Dictionary model = new GSLMS.Entity.Dictionary();
               if (dr["ID"] != null && dr["ID"].ToString() != "")
               {
                   model.ID = OracleHelper.ToLong(dr["ID"].ToString());
               }
               if (dr["PID"] != null && dr["PID"].ToString() != "")
               {
                   model.PID = OracleHelper.ToLong(dr["PID"].ToString());
               }
               if (dr["DATATYPE"] != null && dr["DATATYPE"].ToString() != "")
               {
                   model.GroupName = dr["DATATYPE"].ToString();
               }

               if (dr["DATACODE"] != null && dr["DATACODE"].ToString() != "")
               {
                   model.key = dr["DATACODE"].ToString();
               }

               if (dr["DATAVALUE"] != null && dr["DATAVALUE"].ToString() != "")
               {
                   model.Value = dr["DATAVALUE"].ToString();
               }

               if (dr["SORTNO"] != null && dr["SORTNO"].ToString() != "")
               {
                   model.SortNo = OracleHelper.ToInt(dr["SORTNO"].ToString());
               }

               if (dr["STATUS"] != null && dr["STATUS"].ToString() != "")
               {
                   model.LangType = OracleHelper.ToInt(dr["STATUS"].ToString());
               }

               if (dr["DATAVALUE"] != null && dr["DATAVALUE"].ToString() != "")
               {
                   model.Title = dr["DATAVALUE"].ToString();
               }

               model.Remark = "";
               model.GenerateKey = "";

               return model;
           }
           else
           {
               return null;
           }
       }

       private DataTable GetAllByCache()
       {
           DataTable dt = null;
           if (OracleHelper.GetCachecObject("_DistList") != null)
               dt = (DataTable)OracleHelper.GetCachecObject("_DistList");
           if (dt == null || dt.Rows.Count == 0)
           {
               string sql = "";
               sql = "select * from tb_sys_dist";
               DataSet ds = OracleHelper.ExecuteDataset(sql);
               if (ds != null && ds.Tables.Count > 0)
               {
                   dt = ds.Tables[0];
                   OracleHelper.AddCacheObject("_DistList", (object)dt, 0);
               }

           }

           return dt;
       }

       public bool DeleteGroupName(string groupName)
       {
           bool flag = false;
           string sql = "";
           sql = " delete from tb_sys_dist where datatype='" + groupName + "'";

           try
           {
               int num = OracleHelper.ExecuteNonQuery(sql);
               if (num == 1)
               {
                   flag = true;
                   //清除缓存
                   OracleHelper.RemoveCacheObject("_DistList");
               }
           }
           catch (Exception ex)
           {
               log.ExceptionHand(ex);
           }

           return flag;
       }

       public bool IsExits(string groupName, string key)
       {
           bool isExit = false;
           DataTable dt = OracleHelper.DataTableFileter(GetAllByCache(), " datatype='"+groupName+"' and datacode='"+key+"'", "");
           if (dt != null && dt.Rows.Count > 0)
               isExit = true;
           return isExit;
       }

      


    }
}
